package com.zx.mobile.filter;

import com.zx.mobile.SessionHelper;
import com.zx.mobile.domain.MobileUserDomain;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 对请求中未设置sessionId 的url 拦截 并将session中信息进行组装
 * 
 * @author jefferry.lu
 * 
 */
public class UrlRewriteMobileFilter extends HttpServlet implements Filter {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * log
	 */
	private static Logger log = Logger.getLogger(UrlRewriteMobileFilter.class);

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		String uri = req.getRequestURI();
//		log.info("----------check uri---------" + uri
//				+ "--request querystring---" + req.getQueryString());
		if (MobileFilterHelper.urlNotNeedFilter(uri)) {
			filterChain.doFilter(request, response);
			return;
		}
		//对于未上送sessionId请求进行处理   并使用session进行组装
		Object sessionId = request.getParameter("sessionId");
		if (null == sessionId) {
			// 获得mobile用户
			Object object = req.getSession().getAttribute(
					SessionHelper.MOBILEUSER);
			if (null == object) {
				HttpServletResponse httpResponse = (HttpServletResponse) response;
				httpResponse.sendRedirect(req.getContextPath()
						+ "/jsp/mobile/sessionexpire.jsp");
				return;
			} else {
				// 重写url 保证每个请求新增sessionId
				MobileUserDomain user = (MobileUserDomain) object;
//				log.info("----------session key check ----------"
//						+ user.getKeepKey());
				filterChain.doFilter(new MobileRequestWrapper(
						(HttpServletRequest) request, user.getKeepKey()),
						response);
				return;
			}
		}
		filterChain.doFilter(request, response);
		return;

	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

}
